package com.itjeffrey.autocode.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itjeffrey.autocode.constant.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

/**
 * Redis配置
 *
 * @From: Jeffrey
 * @Date: 2020/11/15
 */
@Slf4j
@Configuration
@EnableCaching //开启缓存
public class RedisConfig extends CachingConfigurerSupport {

    //string serializer
    private RedisSerializer<String> redisSerializer = new StringRedisSerializer();

    //object serializer
    private Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

    public RedisConfig(){
        setObjectMapper(jackson2JsonRedisSerializer);
    }

    @Autowired
    private LettuceConnectionFactory lettuceConnectionFactory;

    /**
     * custom redis cache key
     * eg: UserServiceImpl_getUserNameByLoginName&admin
     * @return
     */
    @Bean
    @Override
    public KeyGenerator keyGenerator(){
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getSimpleName());
            sb.append(SysConstant.SPECIAL_CHAR_10 + method.getName());
            for (Object obj : params) {
                sb.append(SysConstant.SPECIAL_CHAR_8 + obj.toString());
            }
            return sb.toString();
        };
    }

    /**
     * custom cacheManager
     * @return
     */
    @Bean
    @Override
    public CacheManager cacheManager() {
        // 设置ObjectMapper(解决查询缓存转换异常问题)
        setObjectMapper(jackson2JsonRedisSerializer);
        // 配置序列化
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
                .fromConnectionFactory(lettuceConnectionFactory)
                .cacheDefaults(redisCacheConfiguration);
        return builder.build();
    }

    /**
     * config redisTemplate---manually add caches
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置ObjectMapper(解决查询缓存转换异常问题)
        setObjectMapper(jackson2JsonRedisSerializer);
        // 设置连接工厂
        template.setConnectionFactory(lettuceConnectionFactory);
        // 配置key, value, hashValue序列化
        template.setKeySerializer(redisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    /**
     * 解决查询缓存转换异常问题
     */
    private void setObjectMapper(Jackson2JsonRedisSerializer jackson2JsonRedisSerializer){
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
    }
}
